Cost Calculation
Class rewritten/fixed by Stuart Beesley February 2024 - since MD2024(5100)
This class is used to calculate the cost of a security using either the average cost or lot-based method. This can be used to produce the cost and gains (both short and long-term) for the security or for individual transactions on the security.
Follows U.S. IRS 'single-category' average cost method.
Basis is pooled (single average for all shares).
long/short-term split is determined by assigning sales to purchases in FIFO order to establish each share’s holding period.
From U.S. IRS Publication 564 for 2009, under Average Basis, for the 'single-category' method:
"Even though you include all unsold shares of a fund in a single category to compute average basis, you may have both short-term and long-term gains or losses when you sell these shares. To determine your holding period, the shares disposed of are considered to be those acquired first." https://www.irs.gov/pub/irs-prior/p564--2009.pdf
There was a 'double-category' method which allowed you to separate short-term and long-term average cost pools, but the IRS eliminated that method on April 1, 2011. NOTE: this class can still compute the available shares in both short-term and long-term pools so the user can manually run the double-category method. This is controlled by CALCULATE_AVG_COST_DOUBLE_CATEGORY - off by default since MD2027.
Notes: - LOT controlled security accounts can have an invalid cost basis. This is primarily when sell txns are not fully/properly matched to buy txns - when this condition is detected then results from the cost calculation should be used with care. - the cost basis for the account will be returned as zero - capital gains will still be calculated, but will be invalid for any sells not fully/properly matched. - A sale's fee is never split: it goes wholly to short-term if any short-term shares were sold, else wholly to long-term. - A buy or sell of zero shares is a manual cost basis adjustment. It is treated like a normal buy / sell: a zero-share buy adds its amount plus fee to the cost basis; a zero-share sell reduces the cost basis by its amount, and its fee does not affect the cost basis. - Tax dates (useTaxDate): the long-term / short-term holding period test uses each buy's and sale's tax date instead of its transaction date, and getListGainsForDateRange returns its sales in tax date order. - Nothing else changes: the cost basis, the order transactions are processed in, stock splits, currency conversion and the as-of date cut all stay on the transaction date. - Selecting sales by tax date is a separate option on getListGainsForDateRange and getSaleGainsForDateRange (selectSalesByTaxDate).
Since
Moneydance 2018.8 (build 1684); Significant upgrade to unified class MD2024(5100)
Parameters
Default: null. Optional. A candidate set of txns for this security account, which saves this calculation scanning the whole book. It is not the authoritative universe: the txns supplied are still filtered to secAccount and to the as-of date, and are copied into this calculation's own set, so the supplied TxnSet is never mutated.
Default: false. When true and this calculation's as-of date is after today, a second calculation dated today is performed - result stored in the currentBalanceCostCalculation property. When the as-of date is today or earlier, currentBalanceCostCalculation is this calculation itself - so with a past as-of date it is NOT a today calculation. Cannot be combined with unRealizedSaleTxn.
Types
Class that references a transaction and number of shares allocated from that transaction. QUANTITY BASIS DIFFERS BY ALLOCATION MODEL - consumers must pick the one they need. The table below is AS SEEN ON A SELL'S buyAllocations; a buy's sellAllocations are the reverse: average cost : sharesAllocated = sale-date, sharesAllocatedAdjusted = buy-date lot controlled: sharesAllocated = buy-date, sharesAllocatedAdjusted = sale-date and both are reversed again between a sell's buyAllocations and a buy's sellAllocations, because allocateLots() and allocateAverageCostSales() each add the pair with the arguments swapped. Refer calculateGainsForPos, the only reader that sees both models.
Data class containing the shares owned, and cost basis upto/asof the date requested. When a LOT controlled security account's cost basis is invalid, then you can expect costBasisAsOf zero, and isCostBasisValid false.
Properties
Determines whether the cost basis for this security account / calculation is invalid. Always false for average cost controlled items (i.e. these always have a valid cost basis). Will be true for LOT controlled security accounts where any sell txns are not fully/properly matched to buy txns. Note: unRealizedSaleTxn will not be validated/included in this result. This property is derived from unmatchedSellTxns.
The security account
Contains a list of sell transactions which have not been full/properly matched to buy txns. Only applies to LOT controlled security accounts. When null then no issues were detected, and the cost basis is considered valid. This determines the isCostBasisInvalid property. Note: unRealizedSaleTxn will not be validated/included in this result. Refer: getInvalidLotMatchSellTxns.
Default: null. Optional. Specify a dummy sell txn that can be used to generate un-realised gains. Will be appended to the list of transactions. Always supply it here, never inside preparedTxns - otherwise it cannot be identified later (so cannot be excluded via excludeSyntheticTxn), it would be lot validated as though it were a real sell, and it would be cut by the as-of date filter.
Default: false. When true the LT/ST holding period test uses the txn's tax date instead of its transaction date, and getListGainsForDateRange returns its sales in tax date order. @since MD2027
Functions
Derive the date range that can be used to describe the transactional range for this security account's cost calculation. asOfDate is important. When null then it is assumed to be today or the most recent transactional date found The start date is derived from the oldest relevant transactional date found. Note: unRealizedSaleTxn can artificially extend the derived asOfDate / returned end date into the future.
Returns the cost (per share) of the shares held as of the given transaction, or as of the last transaction if the given transaction is null. Note: For LOT controlled security accounts, if the cost basis is invalid then zero will be returned.
Returns the overall capital gain information specific to the given sell transaction. The sell transaction must have the security as its 'account' which means the transaction must be the SplitTxn that is assigned to the security account. If the transaction is invalid or null then a zero/error capital gains is returned.
Calculates and then returns a list of individual (simple) CapitalGainResults for all sale txns within the date requested Notes: - the caller should check the status of this cost calculation's isCostBasisInvalid property, along with the status of each returned gain's isValid property to handle invalid capital gains. - Order: when useTaxDate or selectSalesByTaxDate is true the sales are ordered by tax date, then transaction date; sales on the same dates keep this calculation's own order (the sort is stable). Otherwise the gains are in this calculation's own order (transaction date). Either way the unrealised gain (unRealizedSaleTxn), when present, stays last. - Each gain records both options in CapitalGainResult.useTaxDate and CapitalGainResult.selectSalesByTaxDate.
Returns the most recent Position upto/asof requested.
Calculates and returns CapitalGainResult containing the grand total of all fields within the date requested. Notes: - Gains flagged as invalid will be skipped when calculating totals - The result's isValid property will be false if the security account's cost basis is invalid. - Values are normally returned in the security account's parent (investment) account's currency. You should not directly convert these returned totals to another currency, as gains should normally be converted individually to another currency using that gain's txn date. - optionally pass the targetCurrency for each gain to be converted into (using the gain's txn's date). - The method of calculating / totalling the value/basis/gain/LT/ST and conversion to target currency mirror the CapitalGainsReport for consistancy. - refer valuationDate - when enabled, then constant currency mode is enabled and results will mirror the InvestmentPerformanceReport for consistancy.
Returns a SharesOwnedAsOf data class containing the shares owned, and cost basis upto/asof the date requested.
Returns the actual cost basis impact that the specified SplitTxn transaction has on the running cost basis. Note: Only txn(s) that have a bearing on cost basis will return a value - otherwise null will be returned. - LOT controlled sell txns that caused invalid cost basis will return null. - Unfound position(s) will also return null.
Detects whether the specified sell txn is not fully/properly matched to buy txn(s) causing an invalid cost basis. Only applies to lot controlled security accounts